package com.how.config;

import com.google.common.collect.Lists;
import com.how.config.base.DataSourceBase;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

@Configuration
public class BaseDataSourceConfig extends DataSourceBase {

    @Lazy
    @Resource
    ShardingDataSource shardingDataSource;

    @Bean(BASEDATABASE)
    public DataSource getBaseDatasource() throws Exception {
        // 设置默认参数
        ShardingRuleConfiguration shardingRuleConfig = getShardingRuleConfiguration(BASEDATABASE);

        // 设置主从
        List<MasterSlaveRuleConfiguration> masterSlaveRuleConfigs = Lists.newArrayList();
        masterSlaveRuleConfigs.add(getMasterSlaveRuleConfiguration(shardingDataSource, BASEDATABASE));
        shardingRuleConfig.setMasterSlaveRuleConfigs(masterSlaveRuleConfigs);

        // 设置分表，不分库
        // leads_user
        TableRuleConfiguration leadsUserTableRuleConfiguration = getTableRuleConfigurations(
                "base_user",
                "id",
                BASEDATABASE + ".base_user$->{0..1}",
                "base_user$->{id % 2}",
                null,
                "SNOWFLAKE");

        List<TableRuleConfiguration> tableRuleConfigs = Lists.newArrayList();
        tableRuleConfigs.add(leadsUserTableRuleConfiguration);
        shardingRuleConfig.setTableRuleConfigs(tableRuleConfigs);

        return ShardingDataSourceFactory.createDataSource(shardingDataSource.getDataSourceMap(),
                shardingRuleConfig, getProperties());
    }

}